package cn.iocoder.yudao.module.wms.service.inventory.stock;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.wms.controller.admin.inventory.stock.vo.InventoryStockPageReqVO;
import cn.iocoder.yudao.module.wms.controller.admin.inventory.stock.vo.InventoryStockReqVO;
import cn.iocoder.yudao.module.wms.dal.dataobject.inventory.stock.InventoryStockDO;
import cn.iocoder.yudao.module.wms.dal.dataobject.inventoryclassify.InventoryClassifyDO;
import cn.iocoder.yudao.module.wms.dal.mysql.inventory.stock.InventoryStockMapper;
import cn.iocoder.yudao.module.wms.service.inventoryclassify.InventoryClassifyService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;

/**
 * 存货现存量 Service 实现类
 *
 * @author 曾劲松
 */
@Service
@Validated
public class InventoryStockServiceImpl implements InventoryStockService {

    @Resource
    private InventoryStockMapper inventoryStockMapper;
    @Resource
    private InventoryClassifyService inventoryClassifyService;

    @Override
    public InventoryStockDO getInventoryStock(Long id) {
        return inventoryStockMapper.selectById(id);
    }

    @Override
    public PageResult<InventoryStockDO> getInventoryStockPage(InventoryStockPageReqVO pageReqVO) {
        return inventoryStockMapper.selectPage(pageReqVO, getClassifyCondition(pageReqVO.getClassifyId()));
    }

    @Override
    public List<InventoryStockDO> getInventoryStockSimpleList(String query) {
        return inventoryStockMapper.selectList(query);
    }

    @Override
    public Double getInventoryAvailableAmount(InventoryStockReqVO inventoryStockReqVO) {
        return inventoryStockMapper.findAvailableAmount(inventoryStockReqVO);
    }

    /**
     * 获得存货分类条件：查询指定存货分类的子分类编号们，包括自身
     *
     * @param classifyId 存货分类编号
     * @return 存货分类编号集合
     */
    private Set<Long> getClassifyCondition(Long classifyId) {
        if (classifyId == null) {
            return Collections.emptySet();
        }
        Set<Long> classifyIds = convertSet(inventoryClassifyService.getChildInventoryClassifyList(classifyId), InventoryClassifyDO::getId);
        classifyIds.add(classifyId);
        return classifyIds;
    }
}